package org.robot.utils;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.util.List;
import java.util.stream.IntStream;

import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;

public class ExcelUtil {
	
	/**
	 * 写入excel
	 * @param tagList 标题list
	 * @param contentLists 内容list，每一行记录都是一个list，注意和标题顺序对应，所有的list放在一个list中
	 * @param excelPath excel文件，以xls结束
	 */
	public static void writeExcel(List<String> tagList, List<List<String>> contentLists, String excelPath) {
		writeExcel(tagList, contentLists, excelPath, "sheet0");
	}
	
	/**
	 * 写入excel
	 * @param tagList 表头list
	 * @param contentLists 内容list，每一行记录都是一个list，注意和标题顺序对应，所有的内容行list放在一个list中
	 * @param excelPath 目标excel，以xls结束
	 * @param sheetName sheet名称
	 */
	public synchronized static void writeExcel(List<String> tagList, List<List<String>> contentLists, String excelPath, String sheetName) {
		Workbook workbook = createWorkbook(excelPath);
		Sheet sheet = workbook.createSheet(sheetName);
		//写入标题行
		writeRow(sheet.createRow(0), tagList);
		//写入内容行
		IntStream.range(0, contentLists.size()).forEach(i -> writeRow(sheet.createRow(i+1), contentLists.get(i)));
		//写入excel
		try(OutputStream out = new FileOutputStream(excelPath)) {
			workbook.write(out);
		} catch (Exception e) {
			e.printStackTrace();
		} 
	}

	private static Workbook createWorkbook(String excelPath) {
		Workbook workbook = new HSSFWorkbook();
		if (new File(excelPath).exists()) {
			try(FileInputStream in = new FileInputStream(excelPath);) {
				workbook = new HSSFWorkbook(in);
			} catch (Exception e) {
				e.printStackTrace();
			} 
		}
		return workbook;
	}

	/**
	 * 写入行
	 * @param row 行
	 * @param rowList 要写入到行的内容
	 */
	private static void writeRow(Row row, List<String> rowList) {
		IntStream.range(0, rowList.size()).forEach(i -> row.createCell(i).setCellValue(rowList.get(i)));
	}
	
	

}
